package com.yanqu.road.server.cmd;

import com.yanqu.road.AgentServer;
import com.yanqu.road.connect.AgentServerLinkControl;
import com.yanqu.road.pb.server.ServerProto;
import com.yanqu.road.player.Player;
import com.yanqu.road.player.PlayerControl;
import com.yanqu.road.server.TempServer;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.utils.executor.GeneralTask;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Cmd(code = Protocol.A_SERVER_SHUTDOWN, desc = "服务器停服维护")
public class ShutdownServerCmd implements Command {
    private static final Logger log = LogManager.getLogger(ShutdownServerCmd.class.getName());

    private static int minutes;

    private static boolean isRunning;

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {
        ServerProto.ServerShutDownMsg shutDownMsg = ServerProto.ServerShutDownMsg.parseFrom(packet.getBytes());
        minutes = shutDownMsg.getMinute();
        boolean stop = shutDownMsg.getShutdown();
        AgentServer.getInstance().setStop(stop);
        if (stop && !isRunning) {
            isRunning = true;
            TempServer.getTimerExecutorService().scheduleWithFixedDelay(new GeneralTask() {
                @Override
                public void doRun() {
                    if (!AgentServer.getInstance().isStop()) {
                        log.warn("cancel shutdown server");
                        this.cancel(false);
                        isRunning = false;
                        return;
                    }
                    //通知客户端
                    noticeClient();
                    log.warn("{} minute shutdown agent", minutes);
                    minutes -= 1;
                    if (minutes < 0) {
                        log.warn("console shutdown server");

                        //发送给GameServer停服维护 保存数据
                        ServerProto.ServerShutDownMsg.Builder reqMsg= ServerProto.ServerShutDownMsg.newBuilder();
                        reqMsg.setMinute(0);
                        reqMsg.setShutdown(true);
                        YanQuMessage message = YanQuMessageUtils.buildMessage(Protocol.S_SERVER_SHUTDOWN,0, reqMsg);
                        AgentServerLinkControl.routeGame(message);

                        AgentServer.getInstance().stop();
                        Runtime.getRuntime().exit(0);
                        this.cancel(false);
                    }

                }
            }, 0, 60 * 1000, TimeUnit.MILLISECONDS);
        }
    }

    private void noticeClient() {
        ServerProto.ServerStopNoticeMsg.Builder msg = ServerProto.ServerStopNoticeMsg.newBuilder();
        msg.setMinutes(minutes);
        YanQuMessage stopMsg = YanQuMessageUtils.buildMessageByte(Protocol.U_SERVER_STOP_NOTICE, msg.build().toByteArray());
        Map<Long, Player> playerMap = new HashMap<>(PlayerControl.getOnlinePlayerMap());
        for (Map.Entry<Long, Player> dataEntry : playerMap.entrySet()) {
            stopMsg.setPlayerId(dataEntry.getKey());
            AgentServerLinkControl.routeClient(stopMsg);
        }
    }

}
